#!/bin/bash
#
# heartbeat STONITH module for powerman
#
# Usage: powerman-stonith [on|off|reset|status] plug
#
#    $serverhost  - host:port of powerman server (required)
#    $poweroff    - set to 1 if 'reset' should simply power off (optional)
#    $PM_OVERRIDE - (undocumented, for test) override powerman path
#    $PM_VERBOSE  - (undocumented, for test) set to enable verbose debug
#                   (1=stderr, 2=syslog, 3=ha_log)

PATH=/bin:/usr/sbin:$PATH
export PM_VERBOSE=${PM_VERBOSE:-0} # Logging disabled by default
export pm=${PM_OVERRIDE:-pm -h $serverhost}

pmlog () {
	case "$PM_VERBOSE" in
		1) echo "powerman-stonith: $*" >&2 ;;
		2) logger -t heartbeat "powerman-stonith: $*" ;;
		3) ha_logger -t heartbeat "powerman-stonith: $*" ;;
	esac
}

# N.B. agent must not exit 0 if the target is still on! (chaos bz 1439)
# Heartbeat will retry if we fail (don't retry here)
pmoff () {
	local plug=$1
	local state rc

	$pm -0 $plug
	rc=$?
	pmlog "$pm -0 $plug, rc=$rc"
	if [ $rc == 0 ]; then
		# for multi-plug aliases, all must be off (jira TOSS-1962)
		for state in $($pm -qx $plug | awk '{ print $NF }'); do
			if [ "$state" != "off" ]; then
				state="unknown"
				rc=1
				break;
			fi
		done
		pmlog "$pm -q $plug, state=$state, rc=$rc"
	fi
	return $rc  # 0=success
}

pmon () {
	local plug=$1
	local rc

	$pm -1 $plug
	rc=$?
	pmlog "$pm -1 $plug, rc=$rc"
	return $rc  # 0=success
}

pmcycle () {
	local plug=$1
	local rc

	$pm -c $plug
	rc=$?
	pmlog "$pm -c $plug, rc=$rc"
	return $rc  # 0=success
}

case $1 in
gethosts)
	exec $pm -lx
	;;
on)
	pmon $2
	exit $?
	;;
off)
	pmoff $2
	exit $?
	;;
reset)
	if [ "$poweroff" == "1" ]; then
		pmoff $2
		exit $?
	else
		pmcycle $2
		exit $?
	fi
	;;
status)
	exec $pm -l >/dev/null
	;;
getconfignames)
	echo serverhost
	echo poweroff
	exit 0
	;;
getinfo-devid|getinfo-devname|getinfo-devdescr)
	echo "powerman STONITH device"
	exit 0
	;;
getinfo-devurl)
	echo "http://code.google.com/p/powerman"
	exit 0
	;;
getinfo-xml)
	cat <<PMEOL
<parameters>
 <parameter name="serverhost" unique="1" required="1">
  <content type="string" default="localhost:10101"/>
  <shortdesc lang="en">host:port of powerman server</shortdesc>
  <longdesc lang="en">
  Specify the host:port of the powerman server, e.g. pmserver:10101
  </longdesc>
 </parameter>

 <parameter name="poweroff" unique="0" required="0">
  <content type="string" default="0"/>
  <shortdesc lang="en">Power off when given reset command</shortdesc>
  <longdesc lang="en">
  For V1 heartbeat which always resets to fence, power off when given
  the reset command.
  </longdesc>
 </parameter>
</parameters>
PMEOL
	exit 0
	;;
*)
	exit 1
	;;
esac
